package wiki.zimo.servlet;

import wiki.zimo.constant.Constant;
import wiki.zimo.utils.VerifyCodeUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @version v1.0
 * @auther: 子墨
 * @datetime: 2018/10/30 12:20
 * @description: 处理验证码请求的Servlet
 */
@WebServlet(value = "/VerifyCode")
public class VerifyCodeServlet extends BaseServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        VerifyCodeUtils code = new VerifyCodeUtils();
        this.outputImage(code.getImage(), response.getOutputStream());
        HttpSession session = request.getSession();
        // 将验证码存入session
        session.setAttribute(Constant.VERIFY_CODE, code.getContent());
        System.out.println(code.getContent());
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/30 12:37
     * @describe: 输出图片
     * @param: [image, out]
     * @return: void
     * @version v1.0
     */
    private void outputImage(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}
